//
//  SellAbroadViewController.m
//  TerritoryShopkeeper
//
//  Created by 李小龙 on 2018/1/17.
//  Copyright © 2018年 ZDQK. All rights reserved.
//

#import "SellAbroadViewController.h"
#import "TitleSelectionView.h"
#import "FiltrateFirstView.h"
#import "CCPScrollView.h"
#import "GoodsListFiltrateModel.h"
#import "FiltrateRightView.h"
#import "GoodsListFiltrateRightModel.h"
#import "GoodsListModel.h"
#import "GoodsListCommonCell.h"
#import "GoodsListDoubleCell.h"
#import "GoodsDetailViewController.h"
#import "HomeNoticeItem.h"

typedef NS_ENUM(NSInteger, GoodsListShowType) {
    GoodsListShowTypeForCommon,
    GoodsListShowTypeForDouble
};

@interface SellAbroadViewController ()<UITableViewDataSource,UITableViewDelegate,DZNEmptyDataSetSource,DZNEmptyDataSetDelegate>

@property (weak, nonatomic) IBOutlet UITableView *tableView;

@property (nonatomic, strong) TitleSelectionView *titleView;
@property (nonatomic, strong) UIButton *rightButton;
@property (nonatomic, assign) GoodsListShowType showType;

@property (nonatomic, strong) UIView *bannerView;
@property (nonatomic, strong) UIImageView *newImageView;
@property (nonatomic, strong) UILabel *newLabel;
@property (nonatomic, strong) CCPScrollView *ccpView;
@property (nonatomic, strong) FiltrateFirstView *firstView;
@property (nonatomic, strong) GoodsListFiltrateModel *filtrateModel;
@property (nonatomic, strong) FiltrateRightView *rightFiltrateView;
@property (nonatomic, strong) GoodsListFiltrateRightModel *rightModel;

@property (nonatomic, assign) NSInteger leftPage;
@property (nonatomic, strong) NSMutableArray *leftDataSource;
@property (nonatomic, assign) NSInteger rightPage;
@property (nonatomic, strong) NSMutableArray *rightDataSource;
@property (nonatomic, strong) NSMutableArray *noticeListArr;
@end

@implementation SellAbroadViewController
#pragma mark - UIViewController
- (instancetype)init {
    self = [super init];
    if (self) {
        _showType = GoodsListShowTypeForCommon;
        _leftPage = 1;
        _rightPage = 1;
        _filtrateModel = [[GoodsListFiltrateModel alloc] init];
        _filtrateModel.sort = @"1";
        _rightModel = [[GoodsListFiltrateRightModel alloc] init];
        _gcid = @"1";
    }
    return self;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    [self configureUI];
    [self responseBlock];
    
    [self configureData];
    [MBProgressHUD showHUDProgress:self.view animated:YES];
    [self loadNoticeList];
    [self loadNewData];
}
- (void)viewWillLayoutSubviews {
    [super viewWillLayoutSubviews];
    
    self.bannerView.frame = CGRectMake(10, 10, self.view.width - 20, 30);
    self.newImageView.frame = CGRectMake(12, 7, 28, 16);
    self.newLabel.frame = CGRectMake(self.newImageView.right + 1, 0, 35, self.bannerView.height);
    self.firstView.frame = CGRectMake(0, self.bannerView.bottom+10, self.view.width, 44);
    [self.firstView setBorderWithTop:NO left:NO bottom:YES right:NO borderColor:[UIColor colorWithHex:0xE5E5E5 alpha:1.0] borderWidth:1];
}
#pragma mark - Action
- (void)configureUI {
    [self.navigationItem setTitleView:self.titleView];
    __weak typeof(self) weakSelf = self;
    self.titleView.block = ^(NSInteger index) {
        [weakSelf.tableView.mj_footer setHidden:YES];
        switch (index) {
            case 0: {
                [weakSelf loadNewData];
            } break;
            case 1: {
                [weakSelf loadNewData];
            } break;
            default:
                break;
        }
    };
    
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:self.rightButton];
    
    [self.view addSubview:self.bannerView];
    [self.bannerView addSubview:self.newImageView];
    [self.bannerView addSubview:self.newLabel];
    self.ccpView = [[CCPScrollView alloc] initWithFrame:CGRectMake(88, 0, ScreenWidth - 20 - 88 - 20, 30)];
    //self.ccpView.titleArray = [NSArray arrayWithObjects:@"iPhone X 上线无Home键 刘海手机你怎么看？",@"2017年还有10天就要过去了,2018年您准备好了吗?",@"今年双11您预算了几个月的工资？",@"吃鸡如日中天，你更看好哪个公司的吃鸡手游？", nil];
    
    self.ccpView.textFont = TextPingFangFontSize(12);
    self.ccpView.titleColor = [UIColor blackTextColor];
    [self.ccpView clickTitleLabel:^(NSInteger index,NSString *titleString) {
        NSLog(@"%ld-----%@",index,titleString);
    }];
    [self.bannerView addSubview:self.ccpView];
    
    [self.view addSubview:self.firstView];
    
    
    [self.tableView registerNib:[UINib nibWithNibName:@"GoodsListCommonCell" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:@"commonCell"];
    [self.tableView registerClass:[GoodsListDoubleCell class] forCellReuseIdentifier:@"doubleCell"];
    
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        switch (weakSelf.titleView.currentIndex) {
            case 0:
                weakSelf.leftPage = 1;
                break;
            case 1:
                weakSelf.rightPage = 1;
                break;
            default:
                break;
        }
        [weakSelf loadNewData];
    }];
    self.tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        switch (weakSelf.titleView.currentIndex) {
            case 0:
                weakSelf.leftPage++;
                break;
            case 1:
                weakSelf.rightPage++;
                break;
            default:
                break;
        }
        [weakSelf loadNewData];
    }];
    [self.tableView clearExtendCellLine];
    [self.tableView.mj_footer setHidden:YES];
}
- (void)configureData {
    ClassifyFirstModel *firstClassifyModel = [[ClassifyManager shareInstance] getClassifyFirstModelWithGcid:self.gcid];
    self.rightModel.attributeArr = [[ClassifyManager shareInstance] configureFiltrateModel:firstClassifyModel];
}
- (void)responseBlock {
    __weak typeof(self) weakSelf = self;
    self.firstView.block = ^(NSInteger index) {
        switch (index) {
            case 0: {
                weakSelf.filtrateModel.sort = @"1";
                [weakSelf loadNewData];
            } break;
            case 1: {
                weakSelf.filtrateModel.sort = @"2";
                [weakSelf loadNewData];
            } break;
            case 3: {
                [weakSelf showFiltrateRightView];
            } break;
            case 4: {
                weakSelf.filtrateModel.sort = @"3";
                [weakSelf loadNewData];
            } break;
            case 5: {
                weakSelf.filtrateModel.sort = @"4";
                [weakSelf loadNewData];
            } break;
            default:
                break;
        }
    };
}

- (void)rightItemClick {
    if (self.showType == GoodsListShowTypeForCommon) {
        self.showType = GoodsListShowTypeForDouble;
        [self.rightButton setImage:[UIImage imageNamed:@"screen"] forState:UIControlStateNormal];
    } else {
        self.showType = GoodsListShowTypeForCommon;
        [self.rightButton setImage:[UIImage imageNamed:@"portrait"] forState:UIControlStateNormal];
    }
    [self.tableView reloadData];
}

- (void)showFiltrateRightView {
    __weak typeof(self) weakSelf = self;
    if (!self.rightFiltrateView) {
        self.rightFiltrateView = [[FiltrateRightView alloc] initWithRightModel:self.rightModel block:^(GoodsListFiltrateRightModel *rightModel) {
            weakSelf.rightModel = rightModel;
            [weakSelf loadNewData];
        }];
    }
    [self.rightFiltrateView showFromRight];
}

- (void)setValueForNoticeItemList:(NSMutableArray *)listArr {
    NSMutableArray *strArr = [NSMutableArray array];
    for (HomeNoticeItem *item in listArr) {
        [strArr addObject:item.ntitle];
    }
    self.ccpView.titleArray = strArr;
    self.ccpView.textFont = TextPingFangFontSize(12);
    self.ccpView.titleColor = [UIColor blackTextColor];
}
#pragma mark - 网络请求
- (void)loadNoticeList {
    
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    
    __weak typeof(self) weakSelf = self;
    [MYAFNetworking POST:URL_Get_Notice parameters:parameters success:^(NSURLSessionDataTask * _Nullable task, id  _Nullable responseObject) {
        NSDictionary *responseDic = responseObject;
        NSString *code = [responseDic safeStringForKey:@"code"];
        if (code && [code isEqualToString:@"200"]) {
            NSArray *data = [responseDic safeJsonObjectForKey:@"data"];
            [weakSelf.noticeListArr removeAllObjects];
            for (NSDictionary *modelDic in data) {
                HomeNoticeItem *item = [HomeNoticeItem mj_objectWithKeyValues:modelDic];
                [weakSelf.noticeListArr addObject:item];
            }
            [weakSelf setValueForNoticeItemList:weakSelf.noticeListArr];
        } else {
            [MBProgressHUD showError:weakSelf.view title:responseObject[@"message"] code:responseObject[@"code"] animated:YES];
        }
        NSLog(@"%@", responseDic);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nullable error) {
        
    }];
    
}
- (void)loadNewData {
//    if (self.titleView.currentIndex == 0) {
//        [MBProgressHUD hideHUDForView:self.view animated:YES];
//        [self.tableView.mj_header endRefreshing];
//        [self.tableView.mj_footer endRefreshing];
//        [self.tableView reloadData];
//        return;
//    }
    NSString *url;
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    switch (self.titleView.currentIndex) {
        case 0:
            [parameters setObject:@(self.leftPage) forKey:@"pageNumber"];
            url = URL_Get_Purchase_Goods_List;
            break;
        case 1:
            [parameters setObject:@(self.rightPage) forKey:@"pageNumber"];
            url = URL_Get_SellAbroad_Goods_List;
            break;
        default:
            break;
    }
    [parameters setObject:PageSize forKey:@"pageSize"];
    
    [parameters setObject:self.filtrateModel.sort forKey:@"sort"]; // 排序(1推荐2销量3价格升4价格降)
    
    [parameters setObject:@"0" forKey:@"isrecommend"]; // 是否推荐(1是0否)
    [parameters setObject:@"0" forKey:@"issalesvolume"]; // 销量(1是0否)
    [parameters setObject:@"0" forKey:@"isprice"]; // 价格(0否1升序2降序)
    [parameters setObject:@"" forKey:@"gcid"];     // 一级分类id集合
    [parameters setObject:@"" forKey:@"gtcid"];    // 二级分类id集合
    [parameters setObject:@"" forKey:@"gtrcid"];   // 三级分类id
    [parameters setObject:self.rightModel.minPrice forKey:@"pricemin"]; // 价格1
    [parameters setObject:self.rightModel.maxPrice forKey:@"pricemax"]; // 价格2
    
    __weak typeof(self) weakSelf = self;
    [MYAFNetworking POST:url parameters:parameters success:^(NSURLSessionDataTask * _Nullable task, id  _Nullable responseObject) {
        [MBProgressHUD hideHUDForView:weakSelf.view animated:YES];
        [weakSelf.tableView.mj_header endRefreshing];
        [weakSelf.tableView.mj_footer endRefreshing];
        NSDictionary *responseDic = responseObject;
        NSString *code = [responseDic safeStringForKey:@"code"];
        
        if (code && [code isEqualToString:@"200"]) {
            NSInteger currentPage = 0;
            NSMutableArray *array;
            switch (weakSelf.titleView.currentIndex) {
                case 0:
                    currentPage = weakSelf.leftPage;
                    array = weakSelf.leftDataSource;
                    break;
                case 1:
                    currentPage = weakSelf.rightPage;
                    array = weakSelf.rightDataSource;
                    break;
                default:
                    break;
            }
            
            NSDictionary *data = [responseDic safeJsonObjectForKey:@"data"];
            NSArray *list = [data safeJsonObjectForKey:@"list"];
            NSString *totalPage = [data safeObjectForKey:@"totalPage"];
            if (currentPage == totalPage.integerValue || totalPage.integerValue == 0) {
                [weakSelf.tableView.mj_footer endRefreshingWithNoMoreData];
                [weakSelf.tableView.mj_footer setHidden:YES];
            } else {
                [weakSelf.tableView.mj_footer resetNoMoreData];
                [weakSelf.tableView.mj_footer setHidden:NO];
            }
            
            if (currentPage == 1) {
                [array removeAllObjects];
            }
            
            for (NSDictionary *modelDic in list) {
                GoodsListModel *model = [GoodsListModel mj_objectWithKeyValues:modelDic];
                [array addObject:model];
            }
            
            [weakSelf.tableView reloadData];
            
        } else {
            [MBProgressHUD showError:weakSelf.view title:[responseDic safeStringForKey:@"message"] code:code animated:YES];
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nullable error) {
        [MBProgressHUD hideHUDForView:weakSelf.view animated:YES];
        [MBProgressHUD showError:weakSelf.view title:@"" code:@"" animated:YES];
    }];
}
#pragma mark - UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    NSMutableArray *array;
    switch (self.titleView.currentIndex) {
        case 0:
            array = self.leftDataSource;
            break;
        case 1:
            array = self.rightDataSource;
            break;
        default:
            break;
    }
    if (self.showType == GoodsListShowTypeForCommon) {
        return array.count;
    } else {
        return [GoodsListDoubleCell getRowNumberWithItemArr:array];
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    NSMutableArray *array;
    __block GoodsDetailViewControllerType deatilType = GoodsDetailViewControllerTypeForAbroad;
    switch (self.titleView.currentIndex) {
        case 0:
            array = self.leftDataSource;
            deatilType = GoodsDetailViewControllerTypeForAbroad;
            break;
        case 1:
            array = self.rightDataSource;
            deatilType = GoodsDetailViewControllerTypeForGroup;
            break;
        default:
            break;
    }
    
    if (self.showType == GoodsListShowTypeForCommon) {
        GoodsListCommonCell *commonCell = [tableView dequeueReusableCellWithIdentifier:@"commonCell" forIndexPath:indexPath];
        GoodsListModel *model = [array objectAtIndex:indexPath.row];
        [commonCell setValueForCellWithModel:model];
        return commonCell;
    } else {
        GoodsListDoubleCell *doubleCell = [tableView dequeueReusableCellWithIdentifier:@"doubleCell" forIndexPath:indexPath];
        NSArray *arr =  [GoodsListDoubleCell getCellItemArr:array withIndexPath:indexPath];
        [doubleCell setValuesForCellWithItems:arr];
        
        __weak typeof(self) weakSelf = self;
        doubleCell.block = ^(NSInteger index) {
            GoodsListModel *model = [arr objectAtIndex:index];
            if (!model.isshelves) {
                [MBProgressHUD showError:weakSelf.view title:@"该商品已下架" code:@"" animated:YES];
                return;
            }
            GoodsDetailViewController *detailVC = [[GoodsDetailViewController alloc] init];
            detailVC.gid = model.gid;
            detailVC.type = deatilType;
            [weakSelf.navigationController pushViewController:detailVC animated:YES];
        };
        
        return doubleCell;
    }
}

#pragma mark - UITableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (self.showType == GoodsListShowTypeForCommon) {
        return [GoodsListCommonCell getHeight];
    } else {
        return [GoodsListDoubleCell getHeight];
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    NSMutableArray *array;
    GoodsDetailViewControllerType deatilType = GoodsDetailViewControllerTypeForAbroad;
    switch (self.titleView.currentIndex) {
        case 0:
            array = self.leftDataSource;
            deatilType = GoodsDetailViewControllerTypeForAbroad;
            break;
        case 1:
            array = self.rightDataSource;
            deatilType = GoodsDetailViewControllerTypeForGroup;
            break;
        default:
            break;
    }
    if (self.showType == GoodsListShowTypeForCommon) {
        GoodsListModel *model = [array objectAtIndex:indexPath.row];
        if (!model.isshelves) {
            [MBProgressHUD showError:self.view title:@"该商品已下架" code:@"" animated:YES];
            return;
        }
        GoodsDetailViewController *detailVC = [[GoodsDetailViewController alloc] init];
        detailVC.gid = model.gid;
        detailVC.type = deatilType;
        [self.navigationController pushViewController:detailVC animated:YES];
    }
}
#pragma mark - DZNEmptyDataSetSource, DZNEmptyDataSetDelegate
//主提示标题
- (NSAttributedString *)titleForEmptyDataSet:(UIScrollView *)scrollView {
    return [[NSAttributedString alloc] initWithString:@"暂无商品"
                                           attributes:@{NSFontAttributeName:[UIFont boldSystemFontOfSize:16.0],
                                                        NSForegroundColorAttributeName:[UIColor grayTextColor]}];
}
- (void)emptyDataSet:(UIScrollView *)scrollView didTapView:(UIView *)view {
    [MBProgressHUD showHUDProgress:self.view animated:YES];
    [self loadNewData];
}
#pragma mark - Get
- (TitleSelectionView *)titleView {
    if (!_titleView) {
        _titleView = [[TitleSelectionView alloc] init];
        [_titleView setFrame:CGRectMake(0, 0, 180, 44)];
        [_titleView setTitleWithArrs:@[@"澳洲代购",@"澳洲团购"]  withShowIndex:0 lineWidth:32];
    }
    return _titleView;
}
- (UIButton *)rightButton {
    if (!_rightButton) {
        _rightButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [_rightButton addTarget:self action:@selector(rightItemClick) forControlEvents:UIControlEventTouchUpInside];
        [_rightButton setImage:[UIImage imageNamed:@"portrait"] forState:UIControlStateNormal];
    }
    return _rightButton;
}
- (UIView *)bannerView {
    if (!_bannerView) {
        _bannerView = [[UIView alloc] init];
        _bannerView.backgroundColor = [UIColor whiteColor];
        _bannerView.layer.cornerRadius = 15;
        _bannerView.clipsToBounds = YES;
    }
    return _bannerView;
}

- (UIImageView *)newImageView {
    if (!_newImageView) {
        _newImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"notice"]];
        _newImageView.size = CGSizeMake(28, 16);
    }
    return _newImageView;
}

- (UILabel *)newLabel {
    if (!_newLabel) {
        _newLabel = [[UILabel alloc] init];
        _newLabel.font = TextPingFangMediumFontSize(16);
        _newLabel.textColor = [UIColor blackTextColor];
        _newLabel.text = @"公告";
    }
    return _newLabel;
}
- (FiltrateFirstView *)firstView {
    if (!_firstView) {
        _firstView = [[FiltrateFirstView alloc] initWithType:FiltrateTypeFour];
    }
    return _firstView;
}
- (NSMutableArray *)leftDataSource {
    if (!_leftDataSource) {
        _leftDataSource = [[NSMutableArray alloc] init];
    }
    return _leftDataSource;
}
- (NSMutableArray *)rightDataSource {
    if (!_rightDataSource) {
        _rightDataSource = [[NSMutableArray alloc] init];
    }
    return _rightDataSource;
}
- (NSMutableArray *)noticeListArr {
    if (!_noticeListArr) {
        _noticeListArr = [[NSMutableArray alloc] init];
    }
    return _noticeListArr;
}
#pragma mark -
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
